package com.filepd.controller;

import cn.hutool.json.JSONObject;
import com.filepd.common.R;
import com.filepd.entity.BlockInfo;
import com.filepd.entity.File;
import com.filepd.service.FileService;
import com.filepd.utils.WeBASEUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Atanycosts
 */
@RestController
@RequestMapping("/chain")
@Slf4j
public class ChainController {


    @Autowired
    private WeBASEUtils weBASEUtils;

    @Autowired
    private FileService fileService;

    /**
     * 所有区块
     *
     * @return
     */
    @GetMapping("/all")
    public R<List<File>> getBlockAll() {
        log.info("所有区块: ");

        List<File> blockAll = fileService.getBlockAll();
        return R.success(blockAll);
    }

    /**
     * 获取所有节点
     * @return
     */
    // FIXME 管理节点 ,暂时用不了
    @GetMapping("/getPointAll")
    public R<String> getPointAll(){
        String pointAll = weBASEUtils.getPointAll();
        return R.success(pointAll);
    }

    /**
     * 根据区块高获得交易信息
     * @param blockNumber
     * @return
     */
    @GetMapping("/blockNumber/{blockNumber}")
    public R<BlockInfo> getBlockNumber(@PathVariable Integer blockNumber) {
        log.info("对应 " + blockNumber + " 区块: ");
        BlockInfo blockInfo = weBASEUtils.getBlockNumber(blockNumber);
        return R.success(blockInfo);
    }

    /**
     * 根据区块Hash获得交易信息
     *
     * @param blockHash
     * @return
     */
    @GetMapping("/blockHash/{blockHash}")
    public R<BlockInfo> getBlockByHash(@PathVariable String blockHash) {
        log.info("对应 " + blockHash + " 区块: ");
        BlockInfo blockInfo = weBASEUtils.getBlockHash(blockHash);
        return R.success(blockInfo);
    }

    /**
     * 得到最新的交易
     * @return
     */
    @GetMapping("/get")
    public R<File> get() {
        File file = fileService.getNewBlock();
        return R.success(file);
    }

    /**
     * set方法
     * @param userName
     * @return
     */
    @PostMapping("/set")
    public R<JSONObject> setTransaction(@RequestParam String userName, String fileName, String fileSize, String fileType) {
        log.info("请求setAll方法: " + userName + fileName + fileSize + fileType);
        JSONObject set = weBASEUtils.set(userName, fileName, fileSize, fileType);
        return R.success(set);
    }
}
